package com.share.service;

import com.share.exception.LoginException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.share.domain.User;

/**
 * @author caifan
 *
 * 2015年3月29日
 */
@Service
public class MyRealm extends AuthorizingRealm{
	@Autowired
	ShiroService shiroService;
	@Autowired
	UserService userService;
	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		//获取当前登录用户名
		//String account = (String) principals.fromRealm(getName()).iterator().next();
//		String account = (String)getAvailablePrincipal(principals);
		Subject subject = SecurityUtils.getSubject();
		String account = (String) subject.getPrincipal();
		User user = userService.queryLoginByUsername(account);
		/*List<Map<String,Object>> roleList = shiroService.getRoles(user);
		for (Map<String, Object> roles : roleList) {
			authorizationInfo.addRole(roles.get("roletype").toString());
			Role role = new Role();
			role.setId(Integer.parseInt((roles.get("id").toString())));
			List<Map<String, Object>> permissionsList = shiroService.getPermissions(role);
			for (Map<String, Object> perms : permissionsList) {
				authorizationInfo.addStringPermission(perms.get("operation").toString());
			}
		}*/
		return authorizationInfo;
	}

	/* (non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		//根据用户名查询数据库
		UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token;//封装认证对象
		User user = userService.queryLoginByUsername(usernamePasswordToken.getUsername());
		if (null == user) {
			return null;
		}
		//返回密码
		AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());//getName获取当前的realm
		//比较密码
		return authenticationInfo;
	}

}
